package com.dengke.springsecurity.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dengke.springsecurity.dao.UserInfoDAO;
import com.dengke.springsecurity.entity.User;
import com.dengke.springsecurity.entity.UserRole;
import com.dengke.springsecurity.model.UserInfo;

@Service("Hibernate")
@Transactional
public class HibernateUserInfoDAOImpl implements UserInfoDAO {

	@Autowired
	private SessionFactory sessionFactory;

	public HibernateUserInfoDAOImpl() {
	}

	@Override
	public UserInfo findUserInfo(String userName) {
		String sql = "select new " + UserInfo.class.getName() + "(u.username,u.password)" + "from "
				+ User.class.getName() + " u where u.username=:username";
		Session session=sessionFactory.getCurrentSession();
		Query query=session.createQuery(sql);
		query.setParameter("username", userName);
		return (UserInfo) query.uniqueResult();

	}

	@Override
	public List<String> getUserRoles(String userName) {
		 String sql = "Select r.userRole "//
	                + " from " + UserRole.class.getName() + " r where r.user.username = :username ";
	 
	        Session session = sessionFactory.getCurrentSession();
	 
	        Query query = session.createQuery(sql);
	        query.setParameter("username", userName);
	         
	        List<String> roles = query.list();
	 
	        return roles;
	}

}
